<template>
  <view class="container">
    <!-- 顶部标签页 -->
    <view class="tabs">
      <view
        v-for="(tab, index) in tabs"
        :key="index"
        class="tab-item"
        :class="{ active: currentTab === index }"
        @tap="switchTab(index)"
      >
        <text class="tab-text">{{ tab.name }}</text>
      </view>
    </view>

    <!-- 优惠券列表 -->
    <scroll-view
      class="coupon-list"
      scroll-y
      @scrolltolower="loadMore"
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 我的优惠券列表 -->
      <block v-if="currentTab === 0">
        <view class="empty-state" v-if="myCoupons.length === 0 && !loading">
<!--          <image src="/static/empty-search.png" class="empty-icon" />-->
          <text class="empty-text">暂无优惠券</text>
          <button class="action-btn" @tap="switchTab(1)">去领取优惠券</button>
        </view>

        <view v-else class="coupon-grid">
          <view 
            v-for="coupon in myCoupons" 
            :key="coupon.id" 
            class="coupon-card my-coupon"
            :class="{
              'invalid': coupon.status !== 'unused',
              'fixed-coupon': coupon.coupon?.type === 'fixed',
              'percent-coupon': coupon.coupon?.type === 'percent',
              'used-coupon': coupon.status === 'used',
              'expired-coupon': coupon.status === 'expired'
            }"
          >
            <view class="coupon-left">
              <view class="coupon-value">
                <template v-if="coupon.coupon?.type === 'fixed'">
                  <text class="currency">¥</text>
                  <text class="amount">{{ coupon.coupon?.discountAmount || 0 }}</text>
                </template>
                <template v-else-if="coupon.coupon?.type === 'percent'">
                  <text class="amount">{{ coupon.coupon?.discountAmount || 0 }}</text>
                  <text class="percent">%</text>
                </template>
              </view>
              <view class="coupon-threshold" v-if="coupon.coupon?.minAmount">
                满{{ coupon.coupon.minAmount }}元可用
              </view>
            </view>
            <view class="coupon-right">
              <view class="coupon-name">{{ coupon.coupon?.name || '优惠券' }}</view>
              <view class="coupon-time">
                有效期至: {{ formatDate(coupon.coupon?.endTime) }}
              </view>
              <view class="coupon-status" v-if="coupon.status !== 'unused'">
                {{ getCouponStatusText(coupon.status) }}
              </view>
            </view>
          </view>
        </view>
      </block>

      <!-- 可购买优惠券列表 -->
      <block v-if="currentTab === 1">
        <view class="empty-state" v-if="availableCoupons.length === 0 && !loading">
<!--          <image src="/static/empty-search.png" class="empty-icon" />-->
          <text class="empty-text">暂无可领取的优惠券</text>
        </view>

        <view v-else class="coupon-grid">
          <view 
            v-for="coupon in availableCoupons" 
            :key="coupon.id" 
            class="coupon-card available-coupon"
            :class="{
              'fixed-coupon': coupon.type === 'fixed',
              'percent-coupon': coupon.type === 'percent'
            }"
          >
            <view class="coupon-left">
              <view class="coupon-value">
                <template v-if="coupon.type === 'fixed'">
                  <text class="currency">¥</text>
                  <text class="amount">{{ coupon.discountAmount || 0 }}</text>
                </template>
                <template v-else-if="coupon.type === 'percent'">
                  <text class="amount">{{ coupon.discountAmount || 0 }}</text>
                  <text class="percent">%</text>
                </template>
              </view>
              <view class="coupon-threshold" v-if="coupon.minAmount">
                满{{ coupon.minAmount }}元可用
              </view>
            </view>
            <view class="coupon-right">
              <view class="coupon-name">{{ coupon.name }}</view>
              <view class="coupon-time">
                有效期至: {{ formatDate(coupon.endTime) }}
              </view>
              <button 
                class="get-btn" 
                @tap="getCoupon(coupon)"
                :disabled="coupon.receiving"
              >
                {{ coupon.receiving ? '领取中...' : '立即领取' }}
              </button>
            </view>
          </view>
        </view>
      </block>

      <!-- 加载状态 -->
      <view class="loading-more" v-if="loading && !refreshing">
        <text>加载中...</text>
      </view>
      <view class="loading-more" v-if="!hasMore && !loading && (myCoupons.length > 0 || availableCoupons.length > 0)">
        <text>没有更多了</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import { 
  listCanBuyCouponUsingGet 
} from '@/backend/couponController';
import { 
  listMyUserCouponVoByPageUsingPost,
  addUserCouponUsingPost
} from '@/backend/userCouponController';
import { tokenStore } from '@/store/tokenStore';
import type { API } from '@/backend/typings.d';

const tokenStoreInstance = tokenStore();

// 标签页配置
const tabs = ref([
  { name: '我的优惠券' },
  { name: '领券中心' }
]);

const currentTab = ref(0);
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);

// 我的优惠券相关
const myCoupons = ref<API.UserCouponVO[]>([]);
const myCurrentPage = ref(1);
const myPageSize = ref(10);

// 可领取优惠券相关
const availableCoupons = ref<API.CouponVO[]>([]);
const availableCurrentPage = ref(1);
const availablePageSize = ref(10);

// 切换标签页
const switchTab = (index: number) => {
  if (currentTab.value === index) return;
  currentTab.value = index;
  
  // 切换标签页时重置分页并加载数据
  if (index === 0) {
    myCurrentPage.value = 1;
    fetchMyCoupons(true);
  } else {
    availableCurrentPage.value = 1;
    fetchAvailableCoupons(true);
  }
};

// 获取我的优惠券
const fetchMyCoupons = async (refresh = false) => {
  if (loading.value && !refresh) return;
  
  if (refresh) {
    myCoupons.value = [];
    myCurrentPage.value = 1;
    hasMore.value = true;
  }
  
  loading.value = true;
  
  try {
    if (!tokenStoreInstance.getToken) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    const res = await listMyUserCouponVoByPageUsingPost({
      current: myCurrentPage.value,
      pageSize: myPageSize.value,
      // 默认只查询有效的优惠券，可以根据需求修改
      status: 'unused'
    });
    
    if (res.code === 0 && res.data) {
      if (refresh) {
        myCoupons.value = res.data.records || [];
      } else {
        myCoupons.value = [...myCoupons.value, ...(res.data.records || [])];
      }
      
      hasMore.value = (res.data.records?.length || 0) >= myPageSize.value;
    } else {
      uni.showToast({
        title: res.message || '获取优惠券失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取我的优惠券失败:', error);
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
    uni.stopPullDownRefresh();
  }
};

// 获取可领取优惠券
const fetchAvailableCoupons = async (refresh = false) => {
  if (loading.value && !refresh) return;
  
  if (refresh) {
    availableCoupons.value = [];
    availableCurrentPage.value = 1;
    hasMore.value = true;
  }
  
  loading.value = true;
  
  try {
    if (!tokenStoreInstance.getToken) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    const res = await listCanBuyCouponUsingGet({
      current: availableCurrentPage.value,
      pageSize: availablePageSize.value
    });
    
    if (res.code === 0 && res.data) {
      const coupons = res.data.records || [];
      
      // 添加领取状态属性
      const couponsWithStatus = coupons.map(coupon => ({
        ...coupon,
        receiving: false
      }));
      
      if (refresh) {
        availableCoupons.value = couponsWithStatus;
      } else {
        availableCoupons.value = [...availableCoupons.value, ...couponsWithStatus];
      }
      
      hasMore.value = (coupons.length) >= availablePageSize.value;
    } else {
      uni.showToast({
        title: res.message || '获取优惠券失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取可领取优惠券失败:', error);
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
    uni.stopPullDownRefresh();
  }
};

// 领取优惠券
const getCoupon = async (coupon: any) => {
  if (!tokenStoreInstance.getToken) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  // 设置领取中状态
  coupon.receiving = true;
  
  try {
    const res = await addUserCouponUsingPost({
      couponId: coupon.id
    });
    
    if (res.code === 0) {
      uni.showToast({
        title: '领取成功',
        icon: 'success'
      });
      
      // 刷新我的优惠券列表
      fetchMyCoupons(true);
      
      // 从可领取列表中移除已领取的优惠券
      availableCoupons.value = availableCoupons.value.filter(item => item.id !== coupon.id);
    } else {
      uni.showToast({
        title: res.message || '领取失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('领取优惠券失败:', error);
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    });
  } finally {
    coupon.receiving = false;
  }
};

// 加载更多
const loadMore = () => {
  if (!hasMore.value || loading.value) return;
  
  if (currentTab.value === 0) {
    myCurrentPage.value++;
    fetchMyCoupons();
  } else {
    availableCurrentPage.value++;
    fetchAvailableCoupons();
  }
};

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true;
  if (currentTab.value === 0) {
    fetchMyCoupons(true);
  } else {
    fetchAvailableCoupons(true);
  }
};

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '无限期';
  
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 获取优惠券状态文本
const getCouponStatusText = (status?: string) => {
  switch (status) {
    case 'unused':
      return '';
    case 'used':
      return '已使用';
    case 'expired':
      return '已过期';
    default:
      return '无效';
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchMyCoupons(true);
});

// 页面显示时刷新数据
onShow(() => {
  if (currentTab.value === 0) {
    fetchMyCoupons(true);
  } else {
    fetchAvailableCoupons(true);
  }
});

// 处理页面下拉刷新
onPullDownRefresh(() => {
  if (currentTab.value === 0) {
    fetchMyCoupons(true);
  } else {
    fetchAvailableCoupons(true);
  }
});
</script>

<style scoped>
.container {
  min-height: 100vh;
  background: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.tabs {
  display: flex;
  background: #fff;
  padding: 0 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 10;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 24rpx 0;
  position: relative;
}

.tab-text {
  font-size: 30rpx;
  color: #666;
  transition: color 0.3s;
}

.tab-item.active .tab-text {
  color: #ff5722;
  font-weight: 500;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background: #ff5722;
  border-radius: 2rpx;
}

.coupon-list {
  flex: 1;
  padding: 20rpx;
}

.coupon-grid {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.coupon-card {
  display: flex;
  border-radius: 16rpx;
  background: #fff;
  overflow: hidden;
  position: relative;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.coupon-card::before {
  content: '';
  position: absolute;
  left: -10rpx;
  top: 50%;
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background: #f5f5f5;
  transform: translateY(-50%);
}

.coupon-card::after {
  content: '';
  position: absolute;
  right: -10rpx;
  top: 50%;
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background: #f5f5f5;
  transform: translateY(-50%);
}

.coupon-left {
  width: 220rpx;
  padding: 30rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  position: relative;
}

.my-coupon .coupon-left {
  background: linear-gradient(135deg, #ff9800, #ff5722);
}

.invalid .coupon-left {
  background: #bdbdbd;
}

.coupon-value {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 28rpx;
  margin-right: 4rpx;
}

.amount {
  font-size: 60rpx;
  font-weight: 700;
  line-height: 1;
}

.coupon-threshold {
  font-size: 24rpx;
  margin-top: 16rpx;
  color: rgba(255, 255, 255, 0.9);
}

.coupon-right {
  flex: 1;
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
}

.coupon-name {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 16rpx;
}

.invalid .coupon-name {
  color: #999;
}

.coupon-time {
  font-size: 24rpx;
  color: #999;
  margin-bottom: 20rpx;
}

.coupon-status {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
  font-size: 26rpx;
  color: #bdbdbd;
  padding: 8rpx 16rpx;
  border: 2rpx solid #bdbdbd;
  border-radius: 24rpx;
  transform: rotate(10deg);
}

.get-btn {
  align-self: flex-start;
  font-size: 26rpx;
  background: #ff5722;
  color: #fff;
  padding: 12rpx 32rpx;
  border-radius: 32rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(255, 87, 34, 0.3);
  transition: all 0.3s;
}

.get-btn[disabled] {
  background: #bdbdbd;
  box-shadow: none;
}

.get-btn:active {
  transform: scale(0.95);
  box-shadow: 0 2rpx 6rpx rgba(255, 87, 34, 0.2);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 120rpx 0;
}

.empty-icon {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 32rpx;
}

.empty-text {
  font-size: 30rpx;
  color: #999;
  margin-bottom: 32rpx;
}

.action-btn {
  background: #ff5722;
  color: #fff;
  font-size: 28rpx;
  padding: 16rpx 40rpx;
  border-radius: 40rpx;
  border: none;
  box-shadow: 0 4rpx 12rpx rgba(255, 87, 34, 0.2);
}

.loading-more {
  text-align: center;
  padding: 32rpx 0;
  font-size: 28rpx;
  color: #999;
}

.percent {
  font-size: 32rpx;
  margin-left: 4rpx;
}

.my-coupon[class*="expired"] .coupon-left,
.my-coupon[class*="used"] .coupon-left {
  background: #bdbdbd;
}

.fixed-coupon .coupon-left {
  background: linear-gradient(135deg, #ff9800, #ff5722);
}

.percent-coupon .coupon-left {
  background: linear-gradient(135deg, #2196F3, #03A9F4);
}

.expired-coupon .coupon-left,
.used-coupon .coupon-left {
  background: #bdbdbd;
}
</style> 